'use strict';

const fs = require('fs');

const { Role } = require('../model');

let imgUrl = '../statics/imgs/imgs01.jpg';



// 希望给所有的ctx挂载上一个方法，这个方法和env.render效果一致
async function getAll(ctx, next) {
    let data = ctx.body = await Role.findAll();
    // ctx.body = data;
    ctx.response.type = 'text/html';
    ctx.render('roles.html', { list: data });
}

async function getById(ctx, next) {
    // 拿到id
    let id = ctx.request.params.id;
    console.log(id);
    let role = await Role.findAll({
        where: {
            id: id
        }
    })
    let res = role.length > 0 ? role[0].dataValues : {}
    console.log(res);
    ctx.body = res;
    // console.log(ctx.kaixin);
}
async function addItem(ctx, next) {
    let obj = ctx.request.body;
    console.log(obj);
    // Role来自于模型文件的名称，同时也是模型名称
    Role.create({
        role_name: obj.rolename
    })


    ctx.body = '新增角色成功';
}
async function updateItem(ctx, next) {
    // 拿到id
    let id = ctx.request.params.id;
    let param = ctx.request.body;

    Role.update({ role_name: param.rolename }, {
        where: {
            id: id
        }
    });

    ctx.body = {
        code: 1000,
        data: null,
        msg: '你更新成功了，你休息吧'
    }

}
async function delItem(ctx, next) {
    let id = ctx.request.params.id;
    Role.destroy({
        where: {
            id: id
        }
    })
    ctx.body = '删除成功';
}

async function index(ctx, next) {
    ctx.body = '主页'
}


async function roleEdit(ctx, next) {
    let id = ctx.request.params.id;
    let role = await Role.findAll({
        where: {
            id: id
        }
    })
    let res = role.length > 0 ? role[0].dataValues : {}

    ctx.render('addRole.html', { res, title: '修改角色' })
}

async function roleAdd(ctx, next) {
    ctx.render('addRole.html', { title: '新增角色' })
}

module.exports = {
    'get /': index,
    'get /roles': getAll,
    'get /roleEdit/:id': roleEdit,
    'get /roleEdit': roleAdd,
    'get /roles/:id': getById,
    'post /roles': addItem,
    'put /roles/:id': updateItem,
    'delete /roles/:id': delItem,
}